// pages/console/console.js
// wxCharts使用说明  https://github.com/xiaolin3303/wx-charts/issues/58
let app = getApp();
var wxCharts = require('../../../utils/wxcharts.js');
var windowWidth = 320;

var pieChart_A = null;//联网状态
var pieChart_B = null;//水卡分类
var areaCharts_C = null;//收入统计面积
var areaCharts_D = null;//业务统计
var pieChart_E = null;//收入占比统计
var pieChart_F = null;//订单占比统计


var dateChose = [{ id: 4, name: '昨天' }, { id: 3, name: '近7天' }, { id: 2, name: '近30天' }, { id: 1, name: '近12月' }];
var payWay = [{ name: '水卡', id: 1 }, { name: '微信', id: 2 }, { name: '支付宝', id: 3 }, { name: '投币', id: 4 }];
var dateType = [
  { name: '设备收入排行榜', index: 0, type: 1 ,data:[],is_loading:false}, 
  { name: '加盟商收入排行榜', index: 0, type: 1, data: [], is_loading: false}, 
  { name: '园区排行榜', index: 0, type: 1, data: [], is_loading: false}];

Page({

  /*** 页面的初始数据*/
  data: {
    dateChose,//昨天 7天 30天 12月
    dateType,//设备-加盟商-园区(排行)
    payWay,//支付方式
    chosePut: 3,//当前选中的 收入统计
    choseWay: 3,//当前选中的 业务统计
    dataCountList:[],
    superior_id:0,//superior_id大于0 加盟商
    dateList: [{ id: 1, name: '昨天' }, { id: 2, name: '近7天' }, { id: 3, name: '近30天' }],//
    all_load:[{
      loading_top:false,
      loading_A: false,
      loading_B: false,
      loading_C: false,
      loading_D: false,
      loading_E: false,
      loading_F: false,
    }],
    devicesRanking:[],//设备收入排行
  },

  /*** 生命周期函数--监听页面加载*/
  onLoad: function (e) {
      var res = wx.getSystemInfoSync();
    windowWidth = res.windowWidth ? res.windowWidth - 30 : windowWidth;
    this.getPartnerInfo();//获取用户信息
    this.getdataAllCount(e);//数据统计
    this.getNewIncomeCount(e, this.data.chosePut);//收入统计
    this.getNewMultipleCount(e, this.data.choseWay);//业务统计
    this.getBusinessStatisticst(e);//饼图 收入统计&&订单统计
  },
  onReady: function (e) {
    
  },
  //时间选择
  bindDateChange(e){
    let { index } = e.currentTarget.dataset;
    var dateType = this.data.dateType;
    dateType[index].index = e.detail.value;
      this.setData({
        dateType,
      })
    var type = dateType[index].type;
    var date = this.data.dateList[e.detail.value].id
    //type date
    if (index == 0) {
      this.getDeviceRanking(type,date);//设备收入排行
    } else if (index == 1) {
      this.getPartnerRanking(type, date);//加盟商列表
    } else if (index == 2) {
      this.getVillageRanking(type,date);//园区
    }
  },
  //选择
  choseType(e){
    let { index,tindex,id } = e.currentTarget.dataset;
    var dateType = this.data.dateType;
    dateType[index].type=id;
    this.setData({
      dateType
    })
    const curi = dateType[index].index;
    const date = this.data.dateList[curi].id
    //type date
    if (index==0){ 
      this.getDeviceRanking(id, date);//设备收入排行
    }else if(index==1){
      this.getPartnerRanking(id, date);//加盟商列表
    }else if(index==2){
      this.getVillageRanking(id, date);//园区
    }
    
  },
  //选择日期(收入&&业务统计)  
  choseData(e){
    let { id, kind } = e.currentTarget.dataset;
    if (kind == 1) {//kind=1收入
      this.setData({chosePut:id});
      this.getNewIncomeCount(e,id,true);
    } else if (kind == 2) {//2业务统计
      this.setData({ choseWay:id });
      this.getNewMultipleCount(e, id, true);
    }
    

  },
  touchHandler_A: function (e) {
    console.log(pieChart_A.getCurrentDataIndex(e));
  },  
  //创建设备状态
  buildEcherts_A(e,data) {
    const doubWidth = windowWidth*0.485;
    pieChart_A = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas_A',
      type: 'ring',
      series: data,
      width: doubWidth,
      height: 180,
      dataLabel: false,//是否在图表中显示数据内容值
      padding: 0,
      extra: {
        ringWidth: 15,//圆环宽度，单位为px
      }
    });
  },
  touchHandler_B: function (e) {
    console.log(pieChart_B.getCurrentDataIndex(e));
  },
  //创建水卡分类
  buildEcherts_B(e, data) {
    const doubWidth = windowWidth * 0.485;
    pieChart_B = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas_B',
      type: 'ring',
      series: data,
      width: doubWidth,
      height: 180,
      dataLabel: false,//是否在图表中显示数据内容值
      padding: 0,
      extra: {
        ringWidth: 12,//圆环宽度，单位为px
      }
    });
  },
  //收入统计
  touchHandler_C: function (e) {
    areaCharts_C.scrollStart(e);
  },
  moveHandler_C: function (e) {
    areaCharts_C.scroll(e);
  },
  touchEndHandler_C: function (e) {
    areaCharts_C.scrollEnd(e);
    areaCharts_C.showToolTip(e, {
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  //更新数据
  renewData_C(e, all){
    areaCharts_C.updateData({
      categories: all.abscissa,
      series: [{
        name: all.data[0].name,
        data: all.data[0].data,
        color: "#4EB7FF",
        format: function (val, name) {
          return Number(val).toFixed(2) + '元';
        }
      }, {
        name: all.data[1].name,
        data: all.data[1].data,
        color: "#FF6565",
        format: function (val, name) {
          return Number(val).toFixed(2) + '元';
        }
      }, {
        name: all.data[2].name,
        data: all.data[2].data,
        color: "#FD8E51",
        format: function (val, name) {
          return Number(val).toFixed(2) + '元';
        }
      }]
    });
  },
  //创建收入统计
  buildEcherts_C (e,all) {
    areaCharts_C = new wxCharts({
      canvasId: 'areaCanvas_C',
      type: 'area',
      categories: all.abscissa,
      animation: true,
      series: [{
        name: all.data[0].name,
        data: all.data[0].data,
        color:"#4EB7FF",
        format: function (val, name) {
          return Number(val).toFixed(2) + '元';
        }
      }, {
        name: all.data[1].name,
        data: all.data[1].data,
        color: "#FF6565",
        format: function (val, name) {
          return Number(val).toFixed(2) + '元';
        }
      }, {
        name: all.data[2].name,
        data: all.data[2].data,
        color: "#FD8E51",
        format: function (val, name) {
          return Number(val).toFixed(2)+ '元';
        }
      }],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        gridColor: '#E7EEFD',
        format: function (val) {
          return val;
        },
        min: 0,
        max: 5,
      },
      width: windowWidth,
      height: 214,
      dataLabel: false,//是否在图表中显示数据内容值
      dataPointShape: false,//是否设置提示点
      enableScroll: false,//是否可以滚动 
      background: '#F7FBFF',
      extra: {
        lineStyle: 'curve',//曲线  默认是直线
        column:{
          width: 1,//每项的图形宽度
        }
      }
    });
  },
  //收入统计
  touchHandler_D: function (e) {
    areaCharts_D.scrollStart(e);
  },
  moveHandler_D: function (e) {
    areaCharts_D.scroll(e);
  },
  touchEndHandler_D: function (e) {
    areaCharts_D.scrollEnd(e);
    areaCharts_D.showToolTip(e, {
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  //更新数据
  renewData_D(e, all) {
    areaCharts_D.updateData({
      categories: all.abscissa,
      series: [{
        name: all.data[0].name,
        data: all.data[0].data,
        color: "#4EB7FF",
        format: function (val, name) {
          return val + '台';
        }
      }, {
        name: all.data[1].name,
        data: all.data[1].data,
        color: "#FF6565",
        format: function (val, name) {
          return val + '张';
        }
      }, {
        name: all.data[2].name,
        data: all.data[2].data,
        color: "#FD8E51",
        format: function (val, name) {
          return val + '单';
        }
      }]
    });
  },
  //创建收入统计
  buildEcherts_D(e, all) {
    areaCharts_D = new wxCharts({
      canvasId: 'areaCanvas_D',
      type: 'area',
      categories: all.abscissa,
      animation: true,
      series: [{
        name: all.data[0].name,
        data: all.data[0].data,
        color: "#4EB7FF",
        format: function (val, name) {
          return val + '台';
        }
      }, {
        name: all.data[1].name,
        data: all.data[1].data,
        color: "#FF6565",
        format: function (val, name) {
          return val + '张';
        }
      }, {
        name: all.data[2].name,
        data: all.data[2].data,
        color: "#FD8E51",
        format: function (val, name) {
          return val + '单';
        }
      }],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        gridColor: '#E7EEFD',
        format: function (val) {
          return val;
        },
        min: 0,
        max: 5,
      },
      width: windowWidth,
      height: 214,
      dataLabel: false,//是否在图表中显示数据内容值
      dataPointShape: false,//是否设置提示点
      enableScroll: false,//是否可以滚动 
      background: '#F7FBFF',
      extra: {
        lineStyle: 'curve',//曲线  默认是直线
        column: {
          width: 1,//每项的图形宽度
        }
      }
    });
  },
  //创建------收入占比统计
  buildEcherts_E(e,data){
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth - 30;
    } catch(e) {
      console.error('getSystemInfoSync failed!');
    }
    pieChart_E = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas_E',
      type: 'pie',
      series: data,
      width: windowWidth,
      height: 251,
      dataLabel: true,
      disablePieStroke:true,
    });
  },
  //创建------收入占比统计
  buildEcherts_F(e, data) {
    pieChart_F = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas_F',
      type: 'pie',
      series: data,
      width: windowWidth,
      height: 251,
      dataLabel: true,
      disablePieStroke: true,
    });
  },


  //汇总统计----------数据统计----联网状态----------水卡分类
  getdataAllCount(e) {
    var that = this;
    app.ajax({
      url: 'Partner/Console/dataCount',
      data: {
        type: 0
      },
      success: function (res) {
        console.log('汇总统计', res.data.data)
        if (res.data.code == 1000) {
          var dataCountList = res.data.data.data;
          that.setData({ dataCountList});
          const num_a = that.calculationNum(Number(dataCountList[0].on_line_number), Number(dataCountList[0].off_line_number));
          const num_b = that.calculationNum(Number(dataCountList[3].ordinary_card), Number(dataCountList[3].special_card));
          var ring_A = [
            { name: '在线 ' + num_a[0], color: "#4EB7FF", data: Number(dataCountList[0].on_line_number) }, 
            { name: '离线 ' + num_a[1], color: "#FF6565", data: Number(dataCountList[0].off_line_number) }];
          var ring_B = [
            { name: '普通卡 ' + num_b[0], color: "#4EB7FF", data: Number(dataCountList[3].ordinary_card) }, 
            { name: '特殊卡 ' + num_b[1], color: "#FD8E51", data: Number(dataCountList[3].special_card) }];
          that.buildEcherts_A(e, ring_A);//创建设备状态
          that.buildEcherts_B(e, ring_B);//创建设备状态
        } else {
          app.showToast(res.data.message)
        }
        var all_load = that.data.all_load;
        all_load.loading_top=true;
        setTimeout(() => {
          that.setData({all_load});
        }, 600)
      }
      
    })
  },
  //计算百分比
  calculationNum (num1,num2) {
    const occupy1 = num1 / (num1 + num2);
    const occupy2 = num2 / (num1 + num2);
    return [(occupy1 * 100).toFixed(2) + "%", (occupy2 * 100).toFixed(2) + "%"]
  },
  //收入统计----------
  getNewIncomeCount(e, type,updata=false) {
    var that = this;
    app.ajax({
      url: 'Partner/Console/newIncomeCount',
      data: {type},
      success: function (res) {
        
        var data = res.data.data;
        if (res.data.code == 1000) {
          if (updata) {//是否刷新
            that.renewData_C(e,data);//刷新数据
          }else{
            that.buildEcherts_C(e, data);//重新创建
          }
          
        } else {
          app.showToast(res.data.message)
        }
        var all_load = that.data.all_load;
        all_load.loading_C = true;
        setTimeout(() => {
          that.setData({ all_load });
        }, 600)
      }

    })
  },
  //业务统计----------
  getNewMultipleCount(e, type, updata = false) {
    var that = this;
    app.ajax({
      url: 'Partner/Console/newMultipleCount',
      data: { type },
      success: function (res) {
        var data = res.data.data;
        if (res.data.code == 1000) {
          if (updata) {//是否刷新
            that.renewData_D(e, data);//刷新数据
          } else {
            that.buildEcherts_D(e, data);//重新创建
          }

        } else {
          app.showToast(res.data.message)
        }
        var all_load = that.data.all_load;
        all_load.loading_D = true;
        setTimeout(() => {
          that.setData({ all_load });
        }, 600)
      }

    })
  },

  //饼图 收入占比统计&&订单占比统计
  getBusinessStatisticst(e) {
    var that = this;
    app.ajax({
      url: 'Partner/Console/businessStatistics',
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          var incomeData = res.data.data.income;
          var orderData = res.data.data.order;
          var income = [
            { name: '水卡充值收入', data: Number(incomeData.water_card_recharge)},
            { name: '在线打水收入', data: Number(incomeData.sale_water)},
            { name: '投币打水收入', data: Number(incomeData.coin_water)}];
          var order = [
            { name: '线下支付订单', data: Number(orderData.card_pay)},
            { name: '在线支付订单', data: Number(orderData.online)},
            { name: '投币支付订单', data: Number(orderData.coin)}]
          console.log("income", income, "order", order)
          that.buildEcherts_E(e, income);//收入占比统计
          that.buildEcherts_F(e, order);//订单占比统计
        } else {
          app.showToast(res.data.message)
        }
        var all_load = that.data.all_load;
        all_load.loading_E = true;
        setTimeout(() => {
          that.setData({ all_load });
        }, 600)
        that.getDeviceRanking(1,1);//最后在来调用设备收入排行
        that.getPartnerRanking(1,1);//加盟商收入排行
        that.getVillageRanking(1,1);//园区排行
      }

    })
  },
  //最后的tab列表 设备收入排行  type类型 date日期
  getDeviceRanking(type, date) {
    var that = this;
    var dateType = that.data.dateType;
        dateType[0].is_loading=false;
        that.setData({ dateType });
    app.ajax({
      url: 'Partner/Console/deviceRanking',
      data: { type, date: date.toString()},
      success: function (res) {
        if (res.data.code == 1000) {
          dateType[0].data = res.data.data;
          dateType[0].is_loading = true;
          setTimeout(() => {
            that.setData({ dateType });
          }, 600)
        } else {
          app.showToast(res.data.message)
        }
      }

    })
  },
  //最后的tab列表 加盟商排行  type类型 date日期
  getPartnerRanking(type, date) {
    var that = this;
    var dateType = that.data.dateType;
      dateType[1].is_loading = false;
      that.setData({ dateType });
    app.ajax({
      url: 'Partner/Console/partnerRanking',
      data: { type, date: date.toString() },
      success: function (res) {
        if (res.data.code == 1000) {
          dateType[1].data = res.data.data;
          dateType[1].is_loading = true;
          setTimeout(() => {
            that.setData({ dateType });
          }, 600)
        } else {
          app.showToast(res.data.message)
        }
      }

    })
  },
  //最后的tab列表 园区排行排行  type类型 date日期
  getVillageRanking(type, date) {
    var that = this;
    var dateType = that.data.dateType;
        dateType[2].is_loading = false;
        that.setData({ dateType });
    app.ajax({
      url: 'Partner/Console/villageRanking',
      data: { type, date: date.toString() },
      success: function (res) {
        if (res.data.code == 1000) {
          dateType[2].data = res.data.data;
          dateType[2].is_loading = true;
          setTimeout(() => {
            that.setData({ dateType });
          }, 600)
        } else {
          app.showToast(res.data.message)
        }
        wx.stopPullDownRefresh();
      },
      error: e => {
        wx.stopPullDownRefresh();
      }

    })
  },
  //登录后获取用户信息
  getPartnerInfo() {
    var that = this;
    app.ajax({
      url: 'Partner/User/getPartnerInfo',
      data: {},
      success: function (res) {
        if (res.data.code == 200) {
          that.setData({
            superior_id: res.data.data.superior_id,//superior_id大于0 加盟商
          })
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
      }
    })
  },
  //下拉刷新
  onPullDownRefresh(e) {
    this.getdataAllCount(e);//数据统计
    this.getNewIncomeCount(e, this.data.chosePut,true);//收入统计
    this.getNewMultipleCount(e, this.data.choseWay, true);//业务统计
    this.getBusinessStatisticst(e);//饼图 收入统计&&订单统计
  },
})